package com.k52group.vn.micromarket;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.k52group.vn.micromarket.R;
import com.k52group.vn.micromarket.classes.Profile;
import com.k52group.vn.micromarket.classes.Service;
import com.k52group.vn.micromarket.utils.Constant;
import com.k52group.vn.micromarket.utils.HttpRequest;
import com.k52group.vn.micromarket.utils.Utils;

public class RegisterActivity extends Activity {
	private EditText etcompany, etphone, etemail, etusername, etpassword, etabout, etcontrolcode;
	private TextView ettitle;
	private Spinner spservice;
	private Profile profile = new Profile();
	boolean isEdit = false;
	Button btupdatemylocation, btupdateprofile, btsubsciber;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);

		ettitle = (TextView) findViewById(R.id.tvtitle);
		etcompany = (EditText) findViewById(R.id.EditText07);
		etphone = (EditText) findViewById(R.id.EditText06);
		etemail = (EditText) findViewById(R.id.EditText05);
		etusername = (EditText) findViewById(R.id.EditText04);
		etpassword = (EditText) findViewById(R.id.EditText03);
		etabout = (EditText) findViewById(R.id.EditText02);
		etcontrolcode = (EditText) findViewById(R.id.etcontrolcode);
		spservice = (Spinner) findViewById(R.id.spinner1);

		btupdatemylocation = (Button) findViewById(R.id.Button02);
		btupdateprofile = (Button) findViewById(R.id.Button01);
		btsubsciber = (Button) findViewById(R.id.button1);
		initView();
		new LoadServiceTask(this, spservice).execute();

		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

	}

	private void initView() {
		btsubsciber.setVisibility(View.VISIBLE);
		btupdatemylocation.setVisibility(View.INVISIBLE);
		btupdateprofile.setVisibility(View.VISIBLE);

		String data = getIntent().getStringExtra("data");
		if (data != null) {
			if (!data.equals("")) {
				isEdit = true;
				profile = new Gson().fromJson(data, Profile.class);
				if (profile == null) {
					Utils.saveData(Constant.USER, "", this);
					finish();
					return;
				}
				ettitle.setText("Update Profile");
				etcompany.setText(profile.getYour_company());
				etphone.setText(profile.getPhone());
				etemail.setText(profile.getEmail());
				etusername.setText(profile.getUser_name());
				etcontrolcode.setText(profile.getCtrl_code());
				etpassword.setText(profile.getPassword());
				etabout.setText(profile.getAbout_your_service());
				int selected = getSelected(profile.getService());
				spservice.setSelection(selected);

				btsubsciber.setVisibility(View.VISIBLE);
				btupdatemylocation.setVisibility(View.VISIBLE);
				btupdatemylocation.setText("Update My Location");
				btupdateprofile.setVisibility(View.VISIBLE);
				btupdateprofile.setText("Update Profile");
			}
		}
	}

	public void onClick(View v) {
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		if (v.getId() == R.id.Button01 || v.getId() == R.id.Button02) {
			if (profile == null)
				profile = new Profile();
			profile.setYour_company(etcompany.getText().toString());
			profile.setPhone(etphone.getText().toString());
			profile.setEmail(etemail.getText().toString());
			profile.setUser_name(etusername.getText().toString());
			profile.setPassword(etpassword.getText().toString());
			Service service = (Service) spservice.getSelectedItem();
			if (service == null)
				service = new Service();
			profile.setYour_service(service.getId() + "");
			profile.setAbout_your_service(etabout.getText().toString());
			profile.setCtrl_code(etcontrolcode.getText().toString());

			if (profile.isValidateEmail())
				Toast.makeText(this, "Please input email valid", Toast.LENGTH_SHORT).show();
			else if (profile.isValidate())
				Toast.makeText(this, "Please input username,password", Toast.LENGTH_SHORT).show();
			else if (profile.getCtrl_code().equals(""))
				Toast.makeText(this, "Please input control code", Toast.LENGTH_SHORT).show();
			else {
				if (v.getId() == R.id.Button01)
					new RegisterTask(false).execute();
				else
					new RegisterTask(true).execute();
			}
		}
	}

	private class RegisterTask extends AsyncTask<String, String, String> {
		ProgressDialog dialog;
		boolean isError = false, isUpdateLocation = false;

		public RegisterTask(boolean isUpdateLocation) {
			// TODO Auto-generated constructor stub
			this.isUpdateLocation = isUpdateLocation;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(RegisterActivity.this);
			dialog.setMessage("Register ...");
			if (isEdit)
				dialog.setMessage("Updating ...");
			dialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				HttpRequest request = HttpRequest.post(Constant.URL_REGISTER);

				request.form("regId", Utils.getData(Constant.GCMID, RegisterActivity.this));
				request.form("id", profile.getUserId());
				request.form("username", profile.getUser_name());
				request.form("password", profile.getPassword());
				request.form("company", profile.getYour_company());
				request.form("phone", profile.getPhone());
				request.form("email", profile.getEmail());
				request.form("serivce", profile.getYour_service());
				request.form("about", profile.getAbout_your_service());
				request.form("controlcode", profile.getCtrl_code());
				request.form("dns", Utils.getDeviceID(RegisterActivity.this));

				if (isUpdateLocation || !isEdit) {
					Location location = Utils.getLocation(RegisterActivity.this);
					if (location != null) {
						request.form("lat", location.getLatitude());
						request.form("long", location.getLongitude());
					}
				}

				String body = request.body();
				System.out.println("respone " + body);
				Utils.saveData(Constant.USER, body, RegisterActivity.this);
				profile = new Gson().fromJson(body, Profile.class);
			} catch (Exception e) {
				e.printStackTrace();
				isError = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			String message = isEdit ? "Update false " : "Register false";
			if (isError) {
				Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
			} else {
				if (profile != null) {
					Utils.saveData(Constant.USER, new Gson().toJson(profile), RegisterActivity.this);
					Utils.saveData(Constant.USER_LOGIN, new Gson().toJson(profile), RegisterActivity.this);
					forward();
				} else {
					Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private void forward() {
		Intent it = new Intent(this, SearchActivity.class);
		startActivity(it);
		finish();
		Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
	}

	private int getSelected(String service) {
		int cout = spservice.getCount();
		for (int i = 0; i < cout; i++) {
			Service service2 = (Service) spservice.getAdapter().getItem(i);
			if ((service2.getId() + "").equals(service))
				return i;
		}
		return 0;
	}
}
